#include "usart.h"

/******************************函数区************************************/
void USART1_Config(void)
{
    GPIO_InitTypeDef GPIO_initStructure;
    USART_InitTypeDef USART_initStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);

    // 作为USART的TX端和RX端的引脚初始化
    GPIO_initStructure.GPIO_Pin   = GPIO_Pin_9;
    GPIO_initStructure.GPIO_Mode  = GPIO_Mode_AF_PP; // 复用推挽输出
    GPIO_initStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_initStructure);

    GPIO_initStructure.GPIO_Pin  = GPIO_Pin_10;
    GPIO_initStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; // 浮空输入
    GPIO_Init(GPIOA, &GPIO_initStructure);

    // 配置USART
    USART_initStructure.USART_BaudRate            = 9600;
    USART_initStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_initStructure.USART_Mode                = USART_Mode_Rx | USART_Mode_Tx;
    USART_initStructure.USART_Parity              = USART_Parity_No;
    USART_initStructure.USART_StopBits            = USART_StopBits_1;
    USART_initStructure.USART_WordLength          = USART_WordLength_8b;
    USART_Init(USART1, &USART_initStructure);

    USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);		//串口接收中断
	USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);		//串口空闲中断

    USART_Cmd(USART1, ENABLE);
}

// 内部调用函数，注意要勾选OPTIONS中的USE Micro LIB选项
int fputc(int ch, FILE *f)
{
    USART_SendData(USART1, (u8)ch);
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
    return ch;
}

void usart_send(uint8_t *data, uint8_t len)
{
    uint8_t i;

    for (i = 0; i < len; i++) 
    {
        USART_SendData(USART1, *(data + i));
        while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
    }
}

